import React, { PureComponent, Fragment } from 'react';
import moment from 'moment';
import { connect } from 'dva';
import {
  Button,
  Tag,
  Modal,
  Form,
  message,
  Table,
  Radio,
  Input,
  Icon,
  Drawer,
  Row,
  Col,
  Switch,
  Progress, DatePicker, Select,
} from 'antd';
import MyPagination from '@/components/MyPagination';
import Loading from '@/components/Loading';
import ZImg from 'react-zmage'
import 'react-zmage/lib/zmage.css'
import find from 'lodash/find';
import debounce from 'lodash/debounce';
import { ellipsis, afterCloseModal, DescriptionItem } from '@/utils/utils';
import { routerRedux } from 'dva/router';
import BuildModalTitle from '@/components/BuildModalTitle';
import ReactDataGrid from 'react-data-grid';
import AddOrEditUser from './addOrEditUser';
import AddOrEditReserve from './addOrEditReserve';
import AddOrEditReserve2 from './addOrEditReserve2';
import AddOrEditStatus from './addOrEditStatus';
import request from '@/utils/request';

const FormItem = Form.Item;
const { confirm } = Modal;
const { Option } = Select;

const RadioButton = Radio.Button;

const RadioGroup = Radio.Group;

@connect(({ car_info, loading, global }) => ({
  car_info,
  global,
  loading: loading.models.car_info,
}))
@Form.create()
class BasicList extends PureComponent {
  constructor(props) {
    super(props);
    this.permissions = JSON.parse(sessionStorage.getItem('permissions'));
    this.state = {
      showAddBtn: find(this.permissions, { name: 'device_add_and_edit' }),
      showdelBtn: find(this.permissions, { name: 'device_delete' }),
      showPasswordBtn: find(this.permissions, { name: 'user_default_password_edit' }),
      user_password_reset: find(this.permissions, { name: 'user_password_reset' }),
      visible: false,
      done: false,
      page: 1,
      per_page: 30,
      username: '',
      editRecord: {},
      selectedRowKeys: [],
      users:[]
    };
  }


  componentDidMount() {

    const { dispatch } = this.props;
    const {
      car_info: { pageLoaded, scrollData },
    } = this.props;
    console.log('pageLoaded', pageLoaded);
    const table = document.querySelector('.react-grid-Canvas');
    if (pageLoaded) {
      setTimeout(() => {
        table.scrollTop = scrollData.y;
        table.scrollLeft = scrollData.x;
      }, 0);

    } else {
      const {
        car_info: { searchParams },
      } = this.props;
      console.log('searchParams', searchParams);
      dispatch({
        type: 'car_info/fetch',
        payload: searchParams,
        callback: () => {
          const { dispatch } = this.props;
          dispatch({
            type: 'car_info/changeLoaded',
          });
          dispatch({
            type: 'car_info/changeTableY',
          });
        },
      });

    }
    const that = this;
    // request(`/users`, {
    //   method: 'GET',
    //   params:{
    //     inspector:1,
    //     per_page:100
    //   }
    // }).then((response) => {
    //   if (response.status === 200) {
    //     that.setState({
    //       users: response.data.data,
    //     });
    //   }
    //
    // });
    window.addEventListener('resize', this.resize);
    table.addEventListener('scroll', debounce(this.scroll, 150));
  }

  scroll = (e) => {
    console.log('scroll');
    const { dispatch } = this.props;
    dispatch({
      type: 'car_info/changeScroll',
      payload: {
        x: e.target.scrollLeft,
        y: e.target.scrollTop,
      },
    });
  };

  resize = () => {
    const { dispatch } = this.props;
    dispatch({
      type: 'car_info/changeTableY',
    });
  };
  findChildFunc = (cb) => {
    this.file = cb;
  };

  componentWillUnmount() {
    console.log('componentWillUnmount');
    window.removeEventListener('resize', this.resize);
    const table = document.querySelector('.react-grid-Canvas');
    table.removeEventListener('scroll', debounce(this.scroll, 300));
  }

  handleSearch = (values, cb) => {
    console.log('handleSearch', values);
    const that = this;
    const { dispatch } = this.props;
    dispatch({
      type: 'car_info/fetch',
      payload: {
        ...values,
      },
      callback() {
        console.log('handleSearch callback');
        if (cb) cb();
      },
    });
  };

  renderSimpleForm() {
    const {
      form: { getFieldDecorator },
      car_info: { searchParams },
    } = this.props;
    return (
      <Form layout="inline" className="search-form">
        <FormItem>
          <FormItem label="车牌号">
            {getFieldDecorator('license_plate_number', {
              initialValue: searchParams.license_plate_number,
            })(<Input style={{ width: '150px' }} placeholder="请输入"/>)}
          </FormItem>
          <Button
            type="primary"
            icon='search'
            onClick={() => {
              const { form } = this.props;
              form.validateFields((err, fieldsValue) => {
                if (err) return;

                this.handleSearch({
                  page: 1,
                  per_page: searchParams.per_page,
                  ...fieldsValue,
                });

              });
            }}
          >
            查询
          </Button>
          <Button style={{ marginLeft: 8 }} icon='redo' onClick={this.handleFormReset}>
            重置
          </Button>
          {
            find(this.permissions, { name: 'car_operation' }) &&
            <Button
              icon="car"
              style={{ marginLeft: 8 }}
              type="primary"
              onClick={
                () => {
                  this.setState({
                    addModal: true,
                  });
                }
              }
            >
              添加车辆
            </Button>
          }
        </FormItem>

      </Form>
    );
  }

  handleAdd = () => {
    const formValues = this.AddForm.props.form.getFieldsValue();
    console.log('formValues', formValues);
    let formData = new FormData();
    if(formValues.file){
      formData.append("image", formValues.file.file);
    }
    formData.append("company_id", sessionStorage.getItem('company_id'));
    formData.append("type", formValues.type);
    formData.append("number", formValues.number);
    formData.append("brand", formValues.brand);
    formData.append("passenger_count", formValues.passenger_count);
    formData.append("license_plate_number", formValues.license_plate_number);
    formData.append("remark", formValues.remark);
    formData.append("department_id", formValues.department_id);
    const that = this;
    this.props.dispatch({
      type: 'car_info/add',
      payload: formData,
      callback() {
        message.success('添加车辆成功');
        that.setState({
          addModal: false,
        });
        const {
          car_info: { searchParams },
        } = that.props;
        that.handleSearch(searchParams);
      },
    });
  };

  handleEdit = () => {
    const formValues = this.EditForm.props.form.getFieldsValue();
    console.log('formValues', formValues);
    let formData = new FormData();
    if(formValues.file){
      formData.append("image", formValues.file.file);
    }
    formData.append("company_id", sessionStorage.getItem('company_id'));
    formData.append("type", formValues.type);
    formData.append("number", formValues.number);
    formData.append("brand", formValues.brand);
    formData.append("passenger_count", formValues.passenger_count);
    formData.append("license_plate_number", formValues.license_plate_number);
    formData.append("remark", formValues.remark);
    formData.append("department_id", formValues.department_id);
    const that = this;
    this.props.dispatch({
      type: `car_info/edit`,
      payload: {
        formData,
        id: this.state.editRecord.id,
      },
      callback() {
        message.success('修改车辆成功');
        that.setState({
          editModal: false,
        });
        const {
          car_info: { searchParams },
        } = that.props;
        that.handleSearch(searchParams);
      },
    });
  };
  handleFormReset = () => {
    const { form } = this.props;
    form.resetFields();
    this.handleSearch({
      license_plate_number:'',
      inspector_id:'',
      device_number:'',
      status:'',
      page: 1,
      per_page: 30,
    });
  };

  handleReserve=()=>{
    const formValues = this.ReserveForm.props.form.getFieldsValue();
    console.log('formValues', formValues);
    const state = this.ReserveForm.state;
    console.log('start',state.start)
    console.log('end',state.end)
    let reviewer_ids=[]
    let replicator_ids=[]
    formValues.reviewer_ids.forEach(item => {
      reviewer_ids.push(item.key.split('#')[0]);
    })
    formValues.replicator_ids.forEach(item => {
      replicator_ids.push(item.key.split('#')[0]);
    })
    const that = this;
    request(`/car_applications`, {
      method: 'POST',
      data:{
        car_id:this.state.editRecord.id,
        cause:formValues.cause,
        reviewer_ids,replicator_ids,
        start_time:state.start,
        end_time:state.end
      }
    }).then((response) => {
      if (response.status === 200) {
        message.success('预定车辆成功');
        that.setState({
          reserveModal: false,
        });
        const {
          car_info: { searchParams },
        } = that.props;
        that.handleSearch(searchParams);
      }

    });

  }
  handleStatus=()=>{
    const formValues = this.StatusForm.props.form.getFieldsValue();
    console.log('formValues', formValues);
    const state = this.StatusForm.state;
    console.log('start',state.start)
    console.log('end',state.end)
    const that = this;
    request(`/car_records`, {
      method: 'POST',
      data:{
        car_id:this.state.editRecord.id,
        remark:formValues.remark,
        start_time:state.start,
        end_time:state.end,
        status:state.checked?1:3
      }
    }).then((response) => {
      if (response.status === 200) {
        message.success('修改车辆时间段状态成功');
        that.setState({
          statusModal: false,
        });
        const {
          car_info: { searchParams },
        } = that.props;
        that.handleSearch(searchParams);
      }

    });
  }
  handleCancel = id => {
    const that = this;
    const { dispatch } = this.props;
    dispatch({
      type: `car_info/cancelIssue`,
      payload: { id },
      callback: () => {
        message.success('取消车辆成功');
        const {
          car_info: { searchParams },
        } = that.props;
        that.handleSearch(searchParams);
      },
    });
  };
  handleDelete = id => {
    const that = this;
    const { dispatch } = this.props;
    dispatch({
      type: `car_info/remove`,
      payload: { id },
      callback: () => {
        message.success('删除车辆成功');
        const {
          car_info: { searchParams },
        } = that.props;
        that.handleSearch(searchParams);
      },
    });
  };

  render() {
    const that = this;
    const {
      car_info: { data, loading, tableY, meta, searchParams, selectedRowKeys },
      global: { gridTableW },
    } = this.props;

    const defaultColumnProperties = {
      resizable: true,
    };
    const columns = [
      {
        name: '序号',
        width: 50,
        key: '_index',
        frozen: true,
        formatter: (event) => {
          const {
            car_info: { meta },
          } = this.props;
          return <p className={'index'}>{((meta.current_page - 1) * meta.per_page) + (event.value + 1)}</p>;
        },
      },
      {
        name: '车辆所属部门',
        width: 120,
        frozen: true,
        key: 'department_name',
      },
      {
        name: '司机',
        width: 100,
        frozen: true,
        key: 'driver',
      },
      {
        name: '车辆照片',
        width: 150,
        frozen: true,
        key: 'image_path',
        formatter: (event) => {
          return event.value?<ZImg style={{height:'80px'}}
                                    src={event.value}/>:'';
        },
      },
      {
        name: '车牌号',
        width: 100,
        frozen: true,
        key: 'license_plate_number',
      },
      {
        name: '车辆编号',
        width: 100,
        key: 'number',
      },
      {
        name: '品牌',
        key: 'brand',
        width: 80,
      },
      {
        name: '车辆类型',
        width: 120,
        key: 'type',
      },
      {
        name: '乘坐人数',
        width: 150,
        key: 'passenger_count',
      },
      {
        name: '备注',
        width: 150,
        key: 'remark',
      },
      {
        name: '操作',
        width: 400,
        key: 'right',
        classname: 'operate',
        formatter: (event) => <Fragment>
          {
            event.row.status !== 3 && find(this.permissions, { name: 'car_application_record' }) &&
            <Button
              className={'btn-green'}
              type="primary"
              icon="api"
              size="small"
              onClick={(e) => {
                this.setState({
                  editRecord: event.row,
                  reserveModal: true,
                });
              }
              }
            >车辆预定
            </Button>
          }
          {
            event.row.status!==3&& find(this.permissions, { name: 'car_maintenance' }) &&
            <Button
              type="primary"
              size="small"
              className={'btn-cyan'}
              icon="disconnect"
              onClick={(e) => {
                this.setState({
                  editRecord: event.row,
                  statusModal: true,
                });
              }
              }
            >车辆维护
            </Button>
          }
          {
            event.row.status!==3&& find(this.permissions, { name: 'car_operation' }) &&
            <Button
              type="primary"
              size="small"
              icon="edit"
              onClick={(e) => {
                this.setState({
                  editRecord: event.row,
                  editModal: true,
                });
              }
              }
            >车辆编辑
            </Button>
          }
          {
            event.row.status !== 3 && find(this.permissions, { name: 'car_operation' }) &&
            <Button
              type="danger"
              size="small"
              icon="delete"
              onClick={(e) => {
                confirm({
                  title: `确定要删除 ${event.row.license_plate_number} 吗?`,
                  content: '请谨慎操作！',
                  okText: '确定',
                  okType: 'danger',
                  cancelText: '取消',
                  centered: true,
                  maskClosable: true,
                  onOk() {
                    that.handleDelete(event.row.id);
                  },
                  onCancel() {
                    console.log('Cancel');
                  },
                });
              }
              }
            >删除
            </Button>
          }
        </Fragment>,
      },

    ].map(c => ({ ...defaultColumnProperties, ...c }));

    let totalWidth = 0;
    for (let i = 0; i < columns.length; i++) {
      totalWidth += columns[i].width;
    }
    if (totalWidth < gridTableW) {
      columns[columns.length - 1].width = columns[columns.length - 1].width + gridTableW - totalWidth;
    }

    return <div className="custom-card">
      <div className="table-title"><span className={'title-item'}>车辆信息</span>
      </div>
      <div className="table-page">
        <div className="table-condition">{this.renderSimpleForm()}</div>
        <div className={'table-data-content'}>
          <ReactDataGrid
            columns={columns}
            rowGetter={i => {
              return { ...data[i], _index: i };
            }}
            headerRowHeight={35}
            rowHeight={100}
            rowsCount={data.length}
            minHeight={tableY}
            rowSelection={{
              showCheckbox: false,
              enableShiftSelect: true,
              selectBy: {
                indexes: selectedRowKeys,
              },
            }}
            onRowClick={
              (row) => {
                this.props.dispatch({
                  type: 'car_info/changeSelectRow',
                  payload: [row],
                });
              }
            }

          />
          {
            loading && <Loading/>
          }
        </div>


      </div>
      <div className="table-pagination">
        <MyPagination searchCondition={{ ...searchParams }} meta={meta} handleSearch={this.handleSearch}/>
      </div>
      <Modal
        title={<BuildModalTitle visible={this.state.addModal} modalClass="addModal" title="添加车辆"/>}
        className="addModal"
        visible={this.state.addModal}
        centered
        onCancel={() => {
          this.setState({ addModal: false });
        }}
        width={700}
        onOk={this.handleAdd}
      >
        <AddOrEditUser
          wrappedComponentRef={(inst) => this.AddForm = inst}/>

      </Modal>
      <Modal
        title={<BuildModalTitle visible={this.state.editModal} modalClass="editModal"
                                title={`修改 ${this.state.editRecord.license_plate_number}`}/>}
        destroyOnClose
        visible={this.state.editModal}
        centered
        onOk={this.handleEdit}
        className="editModal"
        width={700}
        afterClose={() => {
          afterCloseModal(); // destroyOnClose需要
        }}
        onCancel={() => {
          this.setState({ editModal: false, editRecord: {} });
        }}

      >
        <AddOrEditUser
          editRecord={this.state.editRecord}
          wrappedComponentRef={(inst) => this.EditForm = inst}/>
      </Modal>

      <Modal
        title={<BuildModalTitle visible={this.state.reserveModal} modalClass="reserveModal"
                                title={`预定 ${this.state.editRecord.license_plate_number}`}/>}
        destroyOnClose
        visible={this.state.reserveModal}
        centered
        onOk={this.handleReserve}
        className="reserveModal"
        width={1200}
        afterClose={() => {
          afterCloseModal(); // destroyOnClose需要
        }}
        onCancel={() => {
          this.setState({ reserveModal: false, editRecord: {} });
        }}

      >
        <AddOrEditReserve2
          editRecord={this.state.editRecord}
          wrappedComponentRef={(inst) => this.ReserveForm = inst}/>
      </Modal>
      <Modal
        title={<BuildModalTitle visible={this.state.statusModal} modalClass="statusModal"
                                title={`车辆维护 ${this.state.editRecord.license_plate_number}`}/>}
        destroyOnClose
        visible={this.state.statusModal}
        centered
        onOk={this.handleStatus}
        className="statusModal"
        width={1200}
        afterClose={() => {
          afterCloseModal(); // destroyOnClose需要
        }}
        onCancel={() => {
          this.setState({ statusModal: false, editRecord: {} });
        }}

      >
        <AddOrEditStatus
          editRecord={this.state.editRecord}
          wrappedComponentRef={(inst) => this.StatusForm = inst}/>
      </Modal>
    </div>;
  }
}

export default BasicList;
